import React, { useState, useEffect } from 'react'
import { Button, Table, Select, Form, Row, Col, Input, DatePicker, Tree, Drawer, Space, Popconfirm, message ,Breadcrumb} from 'antd';
import {CrownOutlined,SolutionOutlined,HistoryOutlined,MessageOutlined,EyeOutlined, SettingOutlined } from '@ant-design/icons'
import roleApi from '../../../apis/role'
import menuApi from '../../../apis/menu'
import moment from 'moment'
import { downloadRoleInfoApi } from "../../../apis/dolw";
export default function role() {

  //表格初始化渲染
  const [totalRole, setTotalRole] = useState(0)
  const [listRole, setListRole] = useState([])
  const pageSize = '50'
  useEffect(() => {
    search()
  }, [])
  function search() {
    const param = { pageSize: pageSize, roleName: '', createTimeFrom: '', createTimeTo: '' }
    roleApi.getAllRoles(param).then(res => {
      if (res.status == 200) {
        setListRole([...res.data.rows])
        setTotalRole(res.data.total)
      }
    })
  }
  //表格标题栏
  const columns = [
    {
      title: '角色',
      dataIndex: 'roleName',
    },
    {
      title: '描述',
      dataIndex: 'remark',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      sorter: (a, b) => Date.parse(a.createTime) - Date.parse(b.createTime)
    },
    {
      title: '修改时间',
      dataIndex: 'modifyTime',
      sorter: (a, b) => Date.parse(a.modifyTime) - Date.parse(b.modifyTime)
    },
    {
      title: '操作',
      render: (record) => 
        <Space size="middle">
          <SettingOutlined onClick={() =>showDrawerEdit(record)} style={{ color: "#60ABF6" }} />
          <EyeOutlined  onClick={()=>showDrawerRoleInfo(record)} style={{ color: "#45BA86" }} />

        </Space>
   
    },
  ];

  //删除功能
  const [delUserInfo, setDelUserInfo] = useState({})
  const rowSelection = {
    onSelect: (record) => {
      setDelUserInfo(record)
    },
  };
  function delRole(delUserInfo) {
    roleApi.delRole(delUserInfo.roleId).then(res => {
      search()
    })
  }
  //搜索及重置功能
  const { RangePicker } = DatePicker;
  const onFinish = (values) => {
    const param = { roleName: '', createTimeFrom: '', createTimeTo: '' }
    if (values.roleName) param.roleName = values.roleName
    if (values.createTime) {
      const createTimeFrom = moment(values.createTime[0]).format("YYYY-MM-DD ")
      const createTimeTo = moment(values.createTime[1]).format("YYYY-MM-DD ")
      param.createTimeFrom = createTimeFrom
      param.createTimeTo = createTimeTo
    }
    roleApi.getAllRoles(param).then(res => {
      setListRole([...res.data.rows])
      setTotalRole(res.data.total)
    })
  };
  const onFinishFailed = (errorInfo) => {
    console.log('Failed:', errorInfo);
  };
  const [form] = Form.useForm()
  function reset() {
    form.resetFields()
    window.location.reload()
  }

  //新增树形控件
  const [expandedKeys, setExpandedKeys] = useState([]);
  const [checkedKeys, setCheckedKeys] = useState([]);
  const [selectedKeys, setSelectedKeys] = useState([]);
  const [autoExpandParent, setAutoExpandParent] = useState(true);
  const onExpand = (expandedKeysValue) => {
    setExpandedKeys(expandedKeysValue);
    setAutoExpandParent(false);
  };
  const onCheck = (checkedKeysValue) => {
    setCheckedKeys(checkedKeysValue);
  };
  const onSelect = (selectedKeysValue, info) => {
    setSelectedKeys(selectedKeysValue);
  };

  //新增角色部分
  const param = {menuName:'',createTimeFrom:'',createTimeTo:''}
  const [treeDataAdd, setTreeDataAdd] = useState([])
  const { TextArea } = Input;
  const [openAdd, setOpenAdd] = useState(false);
  const showDrawer = (e) => {
    menuApi.getRoleMenus(param).then(res => {
      setTreeDataAdd(res.data.rows.children)
    })
    setOpenAdd(true);
  };
  const onCloseAdd = () => {
    setOpenAdd(false);
  };
  const onFinishAddRole = (values) => {
    const menuId = checkedKeys.join()
    values = { ...values, menuId }
    roleApi.addRole(values).then(res => {
      search()
    })
  };
  const onFinishFailedAddRole = (errorInfo) => {
    console.log('Failed:', errorInfo);
  };


  //修改角色部分
  const [roleMenuId,setRoleMenuId] = useState([])
  const onFinishEditRole = (values) => {
    const menuId = roleMenuId.checked.join()
    roleApi.updateRole({...values,menuId}).then(res =>{
      message.success('修改成功')
      search()
    })
  };
  const onFinishFailedEditRole = (errorInfo) => {
    console.log('Failed:', errorInfo);
  };
  const onSelectEdit = (selectedKeys, info) => {
    console.log('selected', selectedKeys, info);
  };
  const onCheckEdit = (checkedKeys, info) => {
    setRoleMenuId(checkedKeys)
    setRoleEditData(checkedKeys)
  };
  const [open,setOpen] = useState(false)
  const [formEdit] = Form.useForm()
  const [roleEditData,setRoleEditData] = useState([])
  const [treeDataEdit,setTreeDataEdit] = useState([])
  const showDrawerEdit = (e) => {
    formEdit.setFieldsValue({
      roleName:e.roleName,
      remark:e.remark
    })
    menuApi.getRoleMenus(param).then(res => {
      setTreeDataEdit(res.data.rows.children)
    })
    roleApi.roleFromMenu(e.roleId).then(res =>{
      setRoleEditData([...res.data])
    })
    setOpen(true);
  };
  const onCloseEdit = () => {
    setOpen(false);
  };
  
  //查看角色信息
  const [openInfo,setOpenInfo] = useState(false)
  const [roleInfo,setRoleInfo] = useState({})
  const [roleInfoData,setRoleInfoData] = useState([])
  const [treeDataInfo,setTreeDataInfo] = useState([])
  const showDrawerRoleInfo = (e) => {
    setRoleInfo(e)
    menuApi.getRoleMenus(param).then(res => {
      setTreeDataInfo(res.data.rows.children)
    })
    roleApi.roleFromMenu(e.roleId).then(res =>{
      setRoleInfoData([...res.data])
    })
    setOpenInfo(true);
  };
  const onCloseInfo = () => {
    setOpenInfo(false);
  };

  //导出excel
  const toExcel = (value) =>{
    if(value==='导出excel'){
      downloadRoleInfoApi()
    }
  }
  return (
  <div style={{ backgroundColor: 'white', width: '100%', padding: '20px 10px' ,boxSizing:'border-box'}}>

    <Breadcrumb>
                <Breadcrumb.Item>系统主页</Breadcrumb.Item>
                <Breadcrumb.Item>
                    系统管理
                </Breadcrumb.Item>
                <Breadcrumb.Item>
                   角色管理
                </Breadcrumb.Item>
            </Breadcrumb>

      {/* 表头搜索栏 */}
      <div style={{marginTop:20}}>
        <Form
          form={form}
          labelCol={{
            span: 4,
          }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
        >
          <Row>
            <Col span={8}>
              <Form.Item
                label="角色："
                name="roleName"
              >
                <Input />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                label='创建时间：'
                name='createTime'
                style={{ marginRight: -500 }}
              >
                <RangePicker style={{ width: 400 }} />
              </Form.Item>
            </Col>
            <Col span={8} >
              <div style={{ textAlign: 'right' }}>
                <Button type="primary" htmlType="submit" size='middle'>
                  查询
                </Button>
                <Button onClick={reset} size='middle'>重置</Button>
              </div>
            </Col>
          </Row>
        </Form>
      </div>

      {/* 表头删除，新增操作等 */}
      <div style={{marginBottom:20}}>
        <Button type='primary' onClick={showDrawer}>新增</Button>
        <Popconfirm
          title={`你确定要删除${delUserInfo.roleName}这条数据吗`}
          onConfirm={() => delRole(delUserInfo)}
          okText="是"
          cancelText="否"
        >
          <Button type='danger'>删除</Button>
        </Popconfirm>
        <Select
          defaultValue="更多操作"
          style={{
            width: 120,
          }}
          onChange={toExcel}
        >
          <Select.Option value='导出excel'>导出excel</Select.Option>
        </Select>
      </div>

      {/* 表格渲染 */}
      <div>
        <Table rowSelection={rowSelection} columns={columns} dataSource={listRole} rowKey='roleId'
          pagination={{ total: totalRole }}
        />
      </div>

      {/* 新增角色 */}
      <Drawer
        title="新增角色"
        width={500}
        onClose={onCloseAdd}
        open={openAdd}
        footer={
          <Space style={{ display: 'flex', justifyContent: 'space-between' }}>
            <Select placeholder='树操作' showArrow={false} style={{ width: 100 }}>
              <Select.Option value='展开所有'>展开所有</Select.Option>
              <Select.Option value='合并所有'>合并所有</Select.Option>
              <Select.Option value='父子关联'>父子关联</Select.Option>
              <Select.Option value='取消关联'>取消关联</Select.Option>
            </Select>
            <Button type="primary" onClick={onCloseAdd}>
              点击关闭
            </Button>
          </Space>
        }
        maskClosable={false}
        closable={false}
      >
        <Form
          onFinish={onFinishAddRole}
          onFinishFailed={onFinishFailedAddRole}
        >
          <Form.Item
            label='角色名称'
            name='roleName'
          >
            <Input />
          </Form.Item>
          <Form.Item
            label='角色描述'
            name='remark'
          >
            <TextArea rows={4} />
          </Form.Item>
          <Form.Item
            label='权限选择'
            name='menuId'
          >
            <Tree
              checkable
              onExpand={onExpand}
              expandedKeys={expandedKeys}
              autoExpandParent={autoExpandParent}
              onCheck={onCheck}
              checkedKeys={checkedKeys}
              onSelect={onSelect}
              selectedKeys={selectedKeys}
              treeData={treeDataAdd}
            />
          </Form.Item>
          <Form.Item
            wrapperCol={{
              offset: 8,
              span: 16,
            }}
          >
            <Button type="primary" htmlType="submit">
              提交
            </Button>
          </Form.Item>
        </Form>
      </Drawer>
      {/* 修改角色 */}
      <Drawer
        title="修改角色"
        width={500}
        onClose={onCloseEdit}
        open={open}
        footer={
          <Space style={{ display: 'flex', justifyContent: 'space-between' }}>
            <Select placeholder='树操作' showArrow={false} style={{ width: 100 }}>
              <Select.Option value='展开所有'>展开所有</Select.Option>
              <Select.Option value='合并所有'>合并所有</Select.Option>
              <Select.Option value='父子关联'>父子关联</Select.Option>
              <Select.Option value='取消关联'>取消关联</Select.Option>
            </Select>
            <Button type="primary" onClick={onCloseEdit}>
              点击关闭
            </Button>
          </Space>
        }
        maskClosable={false}
        closable={false}
      >
         <Form
            form={formEdit}
          onFinish={onFinishEditRole}
          onFinishFailed={onFinishFailedEditRole}
        >
          <Form.Item
            label='角色名称'
            name='roleName'
          >
            <Input />
          </Form.Item>
          <Form.Item
            label='角色描述'
            name='remark'
          >
            <TextArea rows={4} />
          </Form.Item>
          <Form.Item
            label='权限选择'
            name='menuId'
          >
            <Tree
               checkable
               checkStrictly
               expandedKeys={roleEditData}
               checkedKeys={roleEditData}
               onSelect={onSelectEdit}
               onCheck={onCheckEdit}
               treeData={treeDataEdit}
            />
          </Form.Item>
          <Form.Item
            wrapperCol={{
              offset: 8,
              span: 16,
            }}
          >
            <Button type="primary" htmlType="submit">
              提交
            </Button>
          </Form.Item>
        </Form>
      </Drawer>

      {/* 查看角色信息 */}
      <Drawer
        title="角色信息"
        width={500}
        onClose={onCloseInfo}
        open={openInfo}
        footer={
          <Space style={{ display: 'flex', justifyContent: 'space-between' }}>
            <Select placeholder='树操作' showArrow={false} style={{ width: 100 }}>
              <Select.Option value='展开所有'>展开所有</Select.Option>
              <Select.Option value='合并所有'>合并所有</Select.Option>
              <Select.Option value='父子关联'>父子关联</Select.Option>
              <Select.Option value='取消关联'>取消关联</Select.Option>
            </Select>
            <Button type="primary" onClick={onCloseInfo}>
              点击关闭
            </Button>
          </Space>
        }
        maskClosable={false}
        closable={false}
      >
         <p><i style={{marginRight:10}}><CrownOutlined /></i>角色名称：{roleInfo.roleName}</p>
         <p><i style={{marginRight:10}}><MessageOutlined /></i>角色描述：{roleInfo.remark}</p>
         <p><i style={{marginRight:10}}><HistoryOutlined /></i>创建时间：{roleInfo.createTime}</p>
         <p><i style={{marginRight:10}}><HistoryOutlined /></i>修改时间：{roleInfo.modifyTime}</p>
         <div>
          <p><i style={{marginRight:10}}><SolutionOutlined /></i>所拥有的权限：</p>
         <Tree
               checkable
               checkStrictly
               expandedKeys={roleInfoData}
               checkedKeys={roleInfoData}
               onSelect={onSelectEdit}
               onCheck={onCheckEdit}
               treeData={treeDataInfo}
               defaultExpandAll={true}
            />
         </div>
      </Drawer>
 
      </div>
  )
}
